<template>
  <a-spin :spinning="confirmLoading">
    <j-form-container :disabled="formDisabled">
      <a-form :form="form" slot="detail">
        <a-row>

          <a-col :span="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <template #label>
                <span style="color: red; margin-left: 4px;">*</span>
                <span>姓名</span>
              </template>
              <a-input v-decorator="['name', validatorRules.name]" placeholder="请输入姓名"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <template #label>
                <span style="color: red; margin-left: 4px;">*</span>
                <span>车牌号</span>
              </template>
              <a-input v-decorator="['plantNo', validatorRules.plantNo]" placeholder="请输入车牌号"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item :labelCol="labelCol" :wrapperCol="wrapperCol">
              <template #label>
                <span style="color: red; margin-left: 4px;">*</span>
                <span>访客所属单位</span>
              </template>
              <a-input v-decorator="['beifangrenphone', validatorRules.beifangrenphone]" rows="4" placeholder="请输入备注" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="是否为货车" :labelCol="labelCol" :wrapperCol="wrapperCol">

              <a-radio-group v-decorator="['isGoods']" >
                <a-radio-button v-for="item in goodsList" :value="item.value">
                 {{  item.text }}
                </a-radio-button>

              </a-radio-group>


            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="身份证" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['idCardNo', validatorRules.idCardNo]" placeholder="请输入身份证"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="联系方式" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-input v-decorator="['phone', validatorRules.phone]" placeholder="请输入联系方式"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="访问部门" :labelCol="labelCol" :wrapperCol="wrapperCol">

              <a-select v-decorator="['yuyuedept', validatorRules.yuyuedept]" @change="handleSelectChange">
                <a-select-option v-for="(item, index) in departList" :value="item.id" :index="index">
                  {{ item.departName }}
                </a-select-option>
              </a-select>

            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="被访人" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-select v-decorator="['beifangren']">
                <a-select-option v-for="(item, index) in userList" :value="item.username" :index="index">
                  {{ item.realname }}
                </a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="预约时间" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-date placeholder="预约时间" v-decorator="['yuyueshijian']" :trigger-change="true" :show-time="true"
                date-format="YYYY-MM-DD HH:mm:ss" style="width: 100%" />
            </a-form-item>
          </a-col>

          <a-col :span="24">
            <a-form-item label="备注" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <a-textarea v-decorator="['tag']" rows="4" placeholder="请输入备注" />
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="行驶证" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload isMultiple v-decorator="['license', validatorRules.license]"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="行驶证" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload isMultiple v-decorator="['driverLicense']"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="身份证号" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload isMultiple v-decorator="['idCardNoImg']"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="司机签字" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload isMultiple v-decorator="['driverSign']"></j-image-upload>
            </a-form-item>
          </a-col>
          <a-col :span="24">
            <a-form-item label="保安签字" :labelCol="labelCol" :wrapperCol="wrapperCol">
              <j-image-upload isMultiple v-decorator="['sign']"></j-image-upload>
            </a-form-item>
          </a-col>

          <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col>
        </a-row>
      </a-form>
    </j-form-container>
  </a-spin>
</template>

<script>

import { httpAction, getAction } from '@/api/manage'
import pick from 'lodash.pick'
import { validateDuplicateValue } from '@/utils/util'
import store from '@/store'



export default {
  name: 'MenjinrenyuanForm',
  components: {
  },
  props: {
    //流程表单data
    formData: {
      type: Object,
      default: () => { },
      required: false
    },
    //表单模式：true流程表单 false普通表单
    formBpm: {
      type: Boolean,
      default: false,
      required: false
    },
    //表单禁用
    disabled: {
      type: Boolean,
      default: false,
      required: false
    }
  },
  data() {
    return {
      form: this.$form.createForm(this),
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 },
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 },
      },
      confirmLoading: false,
      validatorRules: {
        name: {
          rules: [{ validator: this.validatePass }]
        },
        plantNo: {
          rules: [{ validator: this.validatePass }]
        },
        beifangrenphone: {
          rules: [{ validator: this.validatePass }]
        },

        idCardNo: {
          rules: [{
            message: '请输入正确的身份证号!',
            pattern: /^[1-9][0-9]{5}(19|20)[0-9]{2}((01|03|05|07|08|10|12)(0[1-9]|[1-2][0-9]|3[0-1])|(04|06|09|11)(0[1-9]|[1-2][0-9]|30)|02(0[1-9]|[1-2][0-9]))[0-9]{3}([0-9]|x|X)$/
          }]
        },
        lianxifangshi: {
          rules: [{
            required: true, message: '请输入联系方式!'
          }, {
            validator: this.validatephone,
          }]
        },
        beifangren: {
          rules: [{
            required: true, message: '请输入被访人!'
          }, {
            validator: this.validatebeifangren,
          }]
        },

        yuyueshijian: {
          rules: [{
            required: true, message: '请输入预约时间!'
          }, {
            validator: this.validateyuyueshijian,
          }]
        },


      },
      depar: '',
      url: {
        add: "/menjin/menjinrenyuan/add",
        edit: "/menjin/menjinrenyuan/edit",
        queryById: "/menjin/menjinrenyuan/queryById",
        getUserUrl: 'sys/user/queryUserByDepId',
        getDepartUrl: 'sys/sysDepart/listAll',
      },
      departList: [],
      userList: [],
      goodsList: [  
      { text: '否', value: 0 },  
      { text: '是', value: 1 }  
    ],
    }
  },
  computed: {
    formDisabled() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return false
        }
        return true
      }
      return this.disabled
    },
    showFlowSubmitButton() {
      if (this.formBpm === true) {
        if (this.formData.disabled === false) {
          return true
        }
      }
      return false
    }
  },
  created() {
    //如果是流程中表单，则需要加载流程表单data
    this.showFlowData();
  },
  methods: {
    validatePass(rule, value, callback) {
      let values = this.form.getFieldsValue()

      if (!values.name && !values.plantNo && !values.beifangrenphone) {
        callback(new Error('姓名，车牌号，所属单位请至少输入一项！'))
      }
      callback()
    },
    add() {
      this.edit({});
    },
    async edit(record) {


      let orgCode = store.getters.userInfo.orgCode
     
      await this.getDepart(orgCode)


      this.$nextTick(() => {
        if (!record.yuyuedept) {

          record.yuyuedept = this.model.yuyuedept
        }
        if (!record.beifangren) {
          record.beifangren = store.getters.userInfo.username
        }
        this.form.resetFields();
        this.model = Object.assign({}, record);

        this.visible = true;

        this.$nextTick(() => {
          this.form.setFieldsValue(pick(this.model, 'isGoods', 'beifangren', 'beifangrenphone', 'sign', 'driverSign', 'yuyuedept', 'idCardNoImg', 'license', 'driverLicense', 'admitguid', 'name', 'idCardNo', 'zhaopian', 'phone', 'cheliangleixing', 'cheliangpaifang', 'yuyueshijian'))

        })
      })


    },
    async getDepart(orgCode) {
      console.log("1111111111111111111111");
      console.log(this.url);
      try {
        let res = await getAction(this.url.getDepartUrl)
        console.log(res);
        if (res.success) {
          this.departList = res.result
          this.model.yuyuedept = this.departList.filter(e => e.orgCode == orgCode)[0].id
          console.log(this.model);
          await this.getuser(this.model.yuyuedept)
        }
      } catch (error) {
        console.log(error);

      }





    },
    async getuser(departid) {
      await getAction(this.url.getUserUrl, { id: departid }).then((res) => {
        if (res.success) {
          this.userList = res.result

        }
      })


    },
    //渲染流程表单数据
    showFlowData() {
      if (this.formBpm === true) {
        let params = { id: this.formData.dataId };
        getAction(this.url.queryById, params).then((res) => {
          if (res.success) {
            this.edit(res.result);
          }
        });
      }
    },
    submitForm() {
      const that = this;
      // 触发表单验证
      this.form.validateFields((err, values) => {
        if (!err) {
          that.confirmLoading = true;
          let httpurl = '';
          let method = '';
          if (!this.model.id) {
            httpurl += this.url.add;
            method = 'post';
          } else {
            httpurl += this.url.edit;
            method = 'put';
          }
          let formData = Object.assign(this.model, values);
          console.log("表单提交数据", formData)
          httpAction(httpurl, formData, method).then((res) => {
            if (res.success) {
              that.$message.success(res.message);
              that.$emit('ok');
            } else {
              that.$message.warning(res.message);
            }
          }).finally(() => {
            that.confirmLoading = false;
          })
        }

      })
    },
    popupCallback(row) {
      this.form.setFieldsValue(pick(row, 'isGoods', 'idCardNoImg', 'license', 'driverLicense', 'admitguid', 'name', 'shenfenzheng', 'zhaopian', 'lianxifangshi', 'beifangren', 'beifangrenphone', 'yuyueshijian'))
    },
    handleSelectChange(e) {

      this.userList = []
      this.form.setFieldsValue({
        beifangren: undefined, // 或者 ''，取决于你的需求  
      });

      this.getuser(e)

    },
    handleSelectChange1(e) {

    }
  }
}
</script>